package study.concurrent.thread.controller;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import study.concurrent.thread.service.UserService;
import study.concurrent.thread.support.session.UserContext;
import study.eggs.result.Result;
import study.eggs.result.Results;

import javax.annotation.PreDestroy;
import java.util.Objects;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
public class UserController {

    private ThreadPoolExecutor pool = new ThreadPoolExecutor(10, 10,
            0, TimeUnit.MILLISECONDS,
            new ArrayBlockingQueue<>(100),
            new ThreadFactoryBuilder().setNameFormat("UserInfo-Test-111111-%s").build());

    @Autowired
    private UserService userService;

    @PreDestroy
    public void destroy() {
        if (!Objects.isNull(pool)) {
            log.info(">>>>>> 清理线程池");
            pool.shutdown();
        }
    }

    @RequestMapping("/getUserInfo")
    public Result getUserInfo() {
        pool.submit(() -> {
            log.info(">>>>>> {}", UserContext.get());
            userService.getUserInfo();
        });
        return Results.ok();
    }
}
